package resman.manager;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.hibernate.Session;

import resman.bean.LoginBean;
import resman.database.DatabaseHandler;
import resman.database.TransSession;
import resman.model.Bean;
import resman.model.UserStatus;

@SuppressWarnings("serial")
@ManagedBean(name = "users")
@SessionScoped
public class UserManager extends Bean
{

	private List<LoginBean> users;
	
	@SuppressWarnings("unchecked")
	@PostConstruct
	public void initialize()
	{
		TransSession tsession = DatabaseHandler.openSession(false);
		Session session = tsession.getSession();

		users = session.createQuery("from LoginBean").list();

		tsession.close();
	}
	
	protected LoginBean getUser(int id)
	{
		for (LoginBean user : users)
			if (user.getLoginId() == id)
				return user;
		return null;
	}
	
	protected void changeStatus(Long id, UserStatus status)
	{
		TransSession tsession = DatabaseHandler.openSession(true);
		Session session = tsession.getSession();

		LoginBean user = getUser(id.intValue());
		user.setStatus(status);
		session.merge(user);
		
		tsession.close();
	}
	
	public void activate(Long id)
	{
		changeStatus(id, UserStatus.ACTIVE);
	}
	
	public void deactivate(Long id)
	{
		changeStatus(id, UserStatus.BLOCKED);
	}
	
	public void remove(Long id)
	{
		TransSession tsession = DatabaseHandler.openSession(true);
		Session session = tsession.getSession();
		
		LoginBean user = getUser(id.intValue());
		users.remove(user);
		session.delete(user);
		
		tsession.close();
	}
	
	public List<LoginBean> getUsers()
	{
		return users;
	}

}
